<template>
  <div>
    <Button type="primary" class="back-button" @click="$router.push({name:'ranking-rules-list'})" icon="md-arrow-back">返回上一级</Button>
    <Card>
      <Row>
        <span>计算规则名称：{{model.ruleName}}</span>
      </Row>
      <Row class="m-t-sm">
        <Form ref='model' :model="model" :rules="ruleInline" label-position="right" inline :label-width='100'>
          <FormItem prop='calculateCycle' label="计算周期：">
            <InputNumber v-model="model.calculateCycle" :value="model.calculateCycle" :max="10000" placeholder="请输入" style="width:130px;"></InputNumber>
          </FormItem>
          <!-- <FormItem prop='formual' label="排名公式：">
            <Input v-model="model.formual" clearable placeholder="请输入" style="width:130px;"></Input>
          </FormItem> -->
          <FormItem prop='calculateStartNum' label="开始场次：">
            <InputNumber v-model="model.calculateStartNum" :value="model.calculateStartNum" :min="-1" :max="10000" placeholder="请输入" style="width:130px;"></InputNumber>
          </FormItem>
          <FormItem prop='calculateEndNum' label="结束场次：">
            <InputNumber v-model="model.calculateEndNum" :value="model.calculateEndNum" :max="10000" placeholder="请输入" style="width:130px;"></InputNumber>
          </FormItem>
          <FormItem label="比赛场次限制：" v-if="model.calculateEndNum!=null||model.calculateStartNum!=null">
            <span style="font-weight:bolder;color:red;" v-text="getCalculate()"></span>
          </FormItem>
          <FormItem prop='reduceCycle' label="是否衰减：">
            <i-switch v-model="model.reduceCycle" :value="model.reduceCycle" size="large" :true-value='1' :false-value='0'>
              <span slot="open">是</span>
              <span slot="close">否</span>
            </i-switch>　
          </FormItem>
          <Button @click="save" type="primary" class="m-l-sm">保存</Button>
          <Button v-show="model.reduceCycle===1" @click="editCycle()" type="primary" class="m-l-sm" icon="md-add">新增衰减周期</Button>
        </Form>
      </Row>
      <Row v-show="model.reduceCycle===1" class="m-t-sm">
        <Table :loading="loading" :columns="tableColumn" stripe border :data="model.attenuation"></Table>
        <Modal v-model="visible" width='800' :closable='false' :mask-closable='false' title="编辑">
          <Card>
            <Row>
              <Col span="17" offset="3">
              <Form ref='obj' :model="obj" :rules="rules" inline :label-width='100'>
                <FormItem prop='attenuationStartNum' label="起始周期" style="width:100%;">
                  <InputNumber v-model="obj.attenuationStartNum" :value="obj.attenuationStartNum" :min="0" :max="10000" placeholder="请输入" style="width:100%;"></InputNumber>
                </FormItem>
                <FormItem prop='attenuationEndNum' label="截止周期" style="width:100%;">
                  <InputNumber v-model="obj.attenuationEndNum" :value="obj.attenuationEndNum" :min="0" :max="10000" placeholder="请输入" style="width:100%;"></InputNumber>
                </FormItem>
                <FormItem prop='attenuationRatio' label="衰减率" style="width:100%;">
                  <InputNumber v-model="obj.attenuationRatio" :value="obj.attenuationRatio" :formatter="value => `${value||1}%`" :parser="value => value.replace('%', '')" :min="0" :max="100" placeholder="请输入" style="width:100%;"></InputNumber>
                </FormItem>
              </Form>
              </Col>
            </Row>
          </Card>
          <div slot="footer">
            <Button @click="cancel">取消</Button>
            <Button @click="saveCycle" class="m-l-md" type="primary">确认</Button>
          </div>
        </Modal>
      </Row>
    </Card>
  </div>
</template>
<script>
import dict from "_c/dict/dict.vue";
import dictSpan from "_c/dict/dict-span.vue";
import Api from "@/api/ranking-rules";
import _ from "lodash";
const api = new Api();
export default {
  components: {
    dict,
    dictSpan
  },
  data() {
    return {
      loading: true,
      obj: {},
      objTemp: {
        attenuationStartNum: null,
        attenuationEndNum: null,
        attenuationRatio: 1
      },
      visible: false,
      ruleId: this.$route.params.id,
      model: {
        calculateCycle: null,
        formual: "S",
        calculateStartNum: null,
        calculateEndNum: null,
        reduceCycle: 0,
        attenuation: []
      },
      ruleInline: {
        calculateCycle: [{ required: true, message: "请输入" }],
        // formual: [
        //   {
        //     required: true,
        //     message: "请输入"
        //   }
        // ],
        calculateStartNum: [
          {
            required: true,
            message: "请输入"
          }
        ],
        calculateEndNum: [
          {
            required: false,
            message: "请输入"
          }
        ]
      },
      rules: {
        attenuationStartNum: [{ required: true, message: "请输入" }],
        attenuationEndNum: [
          {
            required: true,
            message: "请输入"
          }
        ],
        attenuationRatio: [
          {
            required: true,
            message: "请输入"
          }
        ]
      },
      pageModel: {},
      tableColumn: [
        {
          title: "序号",
          render: (h, params) => {
            return h("span", params.index + 1);
          }
        },
        {
          title: "周期",
          key: "attenuationStartNum",
          render: (h, params) => {
            return h(
              "span",
              this.$config.toCalculateCycle(
                params.row.attenuationStartNum,
                params.row.attenuationEndNum
              )
            );
          }
        },
        {
          title: "衰减率",
          key: "attenuationRatio",
          render: (h, params) => {
            return h(
              "span",
              this.$config.toPercent(params.row.attenuationRatio)
            );
          }
        },

        {
          title: "操作",
          render: (h, params) => {
            let self = this;
            return h("div", [
              h(
                "Button",
                {
                  style: {
                    marginRight: "5px"
                  },
                  props: { type: "primary", size: "small" },
                  on: {
                    click() {
                      self.editCycle(
                        self.model.attenuation[params.index],
                        params.index
                      );
                    }
                  }
                },
                "编辑"
              ),
              h(
                "Button",
                {
                  props: { type: "error", size: "small" },
                  on: {
                    click() {
                      self.delCycle(params.index);
                    }
                  }
                },
                "删除"
              )
            ]);
          }
        }
      ]
    };
  },
  mounted() {
    this.getCycle();
  },
  methods: {
    getCalculate() {
      let self = this;
      let str = "";
      if (
        self.model.calculateStartNum != null &&
        self.model.calculateEndNum != null
      ) {
        return `${self.model.calculateStartNum}<=N<=${
          self.model.calculateEndNum
        }`;
      }
      if (self.model.calculateStartNum != null) {
        return `${self.model.calculateStartNum}<=N`;
      }
      if (self.model.calculateEndNum != null) {
        return `N<=${self.model.calculateEndNum}`;
      }
    },
    getVal(expression) {
      let self = this;
      eval(expression);
    },
    getCycle() {
      let self = this;
      self.loading = true;
      api
        .queryById(self.ruleId)
        .then(data => {
          if (data.formual == null) {
            data.formual = "S";
          }
          if (data.reduceCycle == null) {
            data.reduceCycle = 0;
          }
          if (data.attenuation) {
            data.attenuation.sort((x, y) => {
              return x.calculateStartNum - y.calculateStartNum;
            });
          }
          self.model = data;
          self.loading = false;
        })
        .catch(error => {
          self.loading = false;
        });
    },
    editCycle(row, index) {
      let self = this;
      self.visible = true;
      if (row == null) {
        self.obj = { ...self.objTemp };
      } else {
        self.obj = {
          ...row,
          attenuationRatio: row.attenuationRatio * 100,
          index
        };
      }
    },
    delCycle(index) {
      this.model.attenuation.splice(index, 1);
    },
    save() {
      let self = this;
      self.$refs["model"].validate(valid => {
        if (valid) {
          self.loading = true;
          api
            .edit(self.model)
            .then(data => {
              self.loading = false;
              self.$router.push("/ranking-rules-management/index");
            })
            .catch(error => {
              self.loading = false;
            });
        }
      });
    },
    saveCycle() {
      let self = this;
      self.$refs["obj"].validate(valid => {
        if (valid) {
          self.loading = true;
          self.obj.attenuationRatio = self.obj.attenuationRatio / 100.0;
          let index = self.obj.index;
          let obj = _.omit(self.obj, ["index"]);
          if (index != null) {
            self.model.attenuation[index] = obj;
            self.model.attenuation = [...self.model.attenuation];
          } else {
            self.model.attenuation.push(obj);
          }
          self.loading = false;
          self.cancel();
        }
      });
    },
    cancel() {
      this.visible = false;
      this.$refs["obj"].resetFields();
    }
  }
};
</script>

